package com.msxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msxt.dto.TokenEntity;
import com.msxt.mapper.TokenDao;
import com.msxt.result.Query;
import com.msxt.service.TokenService;
import com.msxt.utils.CommonUtil;
import com.msxt.utils.PageUtils;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Token服务实现类
 */
@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		Page<TokenEntity> page = this.page(
				new Query<TokenEntity>(params).getPage(),
				new QueryWrapper<>()
		);
		return new PageUtils(page);
	}

	@Override
	public List<TokenEntity> listView(QueryWrapper<TokenEntity> wrapper) {
		return baseMapper.listView(wrapper);
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params, QueryWrapper<TokenEntity> wrapper) {
		Page<TokenEntity> page = new Query<TokenEntity>(params).getPage();
		page.setRecords(baseMapper.listView(page, wrapper));
		return new PageUtils(page);
	}

	@Override
	public String generateToken(Long userid, String username, String tableName, String role) {
		TokenEntity tokenEntity = this.getOne(new QueryWrapper<TokenEntity>()
				.eq("userid", userid)
				.eq("role", role));

		String token = CommonUtil.getRandomString(32);
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.HOUR_OF_DAY, 1);

		if(tokenEntity != null) {
			tokenEntity.setToken(token);
			tokenEntity.setExpiratedtime(cal.getTime());
			this.updateById(tokenEntity);
		} else {
			this.save(new TokenEntity(userid, username, tableName, role, token, cal.getTime()));
		}
		return token;
	}

	@Override
	public TokenEntity getTokenEntity(String token) {
		TokenEntity tokenEntity = this.getOne(new QueryWrapper<TokenEntity>().eq("token", token));
		if(tokenEntity == null || tokenEntity.getExpiratedtime().getTime() < new Date().getTime()) {
			return null;
		}
		return tokenEntity;
	}
}